package cn.donting.jme.swing;

import cn.donting.jme.swing.layout.KeyValueLayout;
import org.jdesktop.swingx.VerticalLayout;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class JKeyValuePanel extends JPanel {

    private List<LinePanel> linePanelList=new ArrayList<>();

    public JKeyValuePanel() {
        setLayout(new VerticalLayout());

    }

    public void add(Component key, Component value){
        LinePanel linePanel = new LinePanel(key, value);
        super.add(linePanel);
        linePanelList.add(linePanel);
    }


    @Override
    public void doLayout() {
        int maxW=0;
        for (LinePanel linePanel : linePanelList) {
            Component key = linePanel.key;
            Dimension preferredSize = key.getPreferredSize();
            maxW=Math.max(preferredSize.width,maxW);
        }
        for (LinePanel linePanel : linePanelList) {
            linePanel.getLayout().setKeyWidth(maxW);
        }
        super.doLayout();
    }

    private static class LinePanel extends JPanel {
        private Component key, value;
        public LinePanel(Component key, Component value) {
            setLayout(new KeyValueLayout());
            add(key, KeyValueLayout.KEY);
            add(value, KeyValueLayout.VALUE);
            this.key=key;
            this.value=value;
        }

        @Override
        public KeyValueLayout getLayout() {
            return (KeyValueLayout)super.getLayout();
        }
    }
}
